<html>

	<head>
		<title>店铺页面管理</title>
		<meta charset="utf-8">
		<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
		<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">

		<link href="../../css/skin/default/style.css" rel="stylesheet" type="text/css" />
		<link href="../../css/dialog.css" rel="stylesheet">
		<link href="../../js/lib/ligerUI/skins/Aqua/css/ligerui-all.css" rel="stylesheet" type="text/css" />

		<script src="../../js/lib/jquery/jquery-1.10.2.min.js" type="text/javascript"></script>

		<script type="text/javascript" src='../../js/plupload/plupload.full.min.js'></script>
		<script src="https://cdn.bootcss.com/json3/3.3.2/json3.min.js"></script>
		<script src="../../js/dialog.js"></script>
		<script src="../../js/JS/layout.js"></script>
		<script src="../../js/constants.js" type="text/javascript"></script>
		<script src="../../js/api.js" type="text/javascript"></script>
		<script src="../../js/qiulib/qiniu.min.js"></script>
		<script type="text/template" class="record_row">
			<li style="border-bottom: 1px solid #f1f1f1;" id={liid}>
				<div id="img" class="aui-li-detail" style="text-align: center;width: 30%;float: left;">{Fname}</div>
				<div class="aui-li-detail" style="text-align: center;width: 10%;float: left;">{Fsize}</div>
				<div class="aui-li-detail" style="text-align: center;width: 50%;float: left;">
					 <div class="progress_sku">
					<div class="progress" id="{Fpg}"><span style="margin-left:10px;float:left;height: 25px; line-height: 25px; color:#fff">0%</span></div>
					 </div>
				</div>
				<div class="aui-li-detail" style="text-align: center;width: 10%;float: left;">
					<a style="margin-top: 5px;width: 80px;" class='listbtn'>上传</a>
				</div>
			</li>
		</script>
		<style>
			.aui-paiming-li-head {
				font-weight: 500;
				font-size: 13px;
			}
			
			.aui-li-detail {
				font-size: 13px;
				min-height: 44px;
				line-height: 44px;
			}
			
			.progress_sku {
				border: 1px solid #f1f1f1;
				border-radius: 25px;
				-moz-border-radius: 25px;
				height: 25px;
				width: 100%;
				margin-top: 10px; 
				/* Old Firefox */
			}
			
			.progress {
				border: 1px solid;
				border-radius: 25px;
				-moz-border-radius: 25px;
				background: #31B807;
				height: 25px;
				width: 0%;
				/* Old Firefox */
			}
		</style>
		<script type="text/javascript">
			var manager;
			var board = {};
			$(document).hover(parent.hindMenu);

			var type = $api.getparastr("atid");

			var pageUrl = BaseUrl + "Video?token=" + $api.getStorage("token");

			var token;
			var domain;

			var config = {
				useCdnDomain: true,
				disableStatisticsReport: false,
				retryCount: 6,
				region: qiniu.region.z0
			};
			var putExtra = {
				fname: "",
				params: {},
				mimeType: null
			};
			$(function() {
				if($api.isEmpty(type)) type = 0;

				initQiuniu();
			});

			var BLOCK_SIZE = 4 * 1024 * 1024;

			function addUploadBoard(file, config, key, type) {
				var id = file.id;
				if(file.size > 100 * 1024 * 1024) {
					$api.showtoast("最大上传文件100M,请不要超过哦！");
					return "";
				}
				var count = Math.ceil(file.size / BLOCK_SIZE);
				var rowLi = $(".record_row").html();
				var filesize = 0;
				if(file.size < 1024)
					filesize = file.size + "字节";
				else if(file.size < (1024 * 1024)) {
					filesize = (file.size / 1024).toFixed(2) + "K";
				} else
					filesize = (file.size / 1024 / 1024).toFixed(2) + "M";
				var newobj = {
					"Fname": key,
					"Fsize": filesize,
					"Fpg": 'pg_' + id,
					"liid": 'li_' + id
				};

				var obj = $api.formatTemplate(newobj, rowLi);

				$(".recode").append(obj);
				return $(".recode").find('#li_' + id);
			}

			function initUpView() {
				var uploadUrl = qiniu.getUploadUrl(config, token);

				var indexCount = 0;
				var resume = false;
				var chunk_size;
				var blockSize;
				var uploader = new plupload.Uploader({
					runtimes: "html5,flash,silverlight,html4",
					url: uploadUrl,
					browse_button: "select", // 触发文件选择对话框的按钮，为那个元素id
					flash_swf_url: "./js/Moxie.swf", // swf文件，当需要使用swf方式进行上传时需要配置该参数
					silverlight_xap_url: "./js/Moxie.xap",
					chunk_size: BLOCK_SIZE,
					max_retries: 3,
					filters: {
						mime_types: [ //只允许上传图片和zip文件
							{
								title: "Vedio files",
								extensions: "mpg,m4v,mp4,flv,3gp,mov,avi,rmvb,mkv,wmv"
							}
						],
						max_file_size: '100m', //最大只能上传400kb的文件
						prevent_duplicates: true //不允许选取重复文件
					},
					multipart_params: {
						// token从服务端获取，没有token无法上传
						token: token
					},
					init: {
						PostInit: function() {
							console.log("upload init");
						},
						FilesAdded: function(up, files) {
							resume = false;
							chunk_size = uploader.getOption("chunk_size");
							var id = files[0].id;
							// 添加上传dom面板

							board[id] = addUploadBoard(files[0], config, files[0].name, "2");
							board[id].start = true;
							//							$(board[id]).find('#pg_' + id).css("width","100%");

							// 绑定上传按钮开始事件
							$(board[id])
								.find(".listbtn")
								.on("click", function() {
									if(board[id].start) {
										uploader.start();
										board[id].start = false;
										$(this).text("取消上传");
									} else {
										uploader.stop();
										board[id].start = true;
										$(this).text("开始上传");
									}
								});
						},
						FileUploaded: function(up, file, info) {
							console.log(info);
						},
						UploadComplete: function(up, files) {
							// Called when all files are either uploaded or failed
							console.log("[完成]");
						},
						Error: function(up, err) {
							console.log(err.response);
						}
					}
				});
				uploader.init();
				uploader.bind('Error', function() {
					console.log(1234)
				})
				uploader.bind("BeforeUpload", function(uploader, file) {
					key = file.name;
					putExtra.params["x:name"] = key.split(".")[0];
					var id = file.id;
					chunk_size = uploader.getOption("chunk_size");
					var directUpload = function() {
						var multipart_params_obj = {};
						multipart_params_obj.token = token;
						// filterParams 返回符合自定义变量格式的数组，每个值为也为一个数组，包含变量名及变量值
						var customVarList = qiniu.filterParams(putExtra.params);
						for(var i = 0; i < customVarList.length; i++) {
							var k = customVarList[i];
							multipart_params_obj[k[0]] = k[1];
						}
						multipart_params_obj.key = key;
						uploader.setOption({
							url: uploadUrl,
							multipart: true,
							multipart_params: multipart_params_obj
						});
					};

					var resumeUpload = function() {
						blockSize = chunk_size;
						initFileInfo(file);
						if(blockSize === 0) {
							mkFileRequest(file)
							uploader.stop()
							return
						}
						resume = true;
						var multipart_params_obj = {};
						// 计算已上传的chunk数量
						var index = Math.floor(file.loaded / chunk_size);

						var headers = qiniu.getHeadersForChunkUpload(token)
						uploader.setOption({
							url: uploadUrl + "/mkblk/" + blockSize,
							multipart: false,
							required_features: "chunks",
							headers: {
								Authorization: "UpToken " + token
							},
							multipart_params: multipart_params_obj
						});
					};
					// 判断是否采取分片上传
					if(
						(uploader.runtime === "html5" ||
							uploader.runtime === "flash") &&
						chunk_size
					) {
						if(file.size < chunk_size) {
							directUpload();
						} else {
							resumeUpload();
						}
					} else {
						console.log(
							"directUpload because file.size < chunk_size || is_android_weixin_or_qq()"
						);
						directUpload();
					}
				});

				uploader.bind("ChunkUploaded", function(up, file, info) {
					var res = JSON.parse(info.response);
					var leftSize = info.total - info.offset;
					var chunk_size = uploader.getOption && uploader.getOption("chunk_size");
					if(leftSize < chunk_size) {
						up.setOption({
							url: uploadUrl + "/mkblk/" + leftSize
						});
					}
					up.setOption({
						headers: {
							Authorization: "UpToken " + token
						}
					});
					// 更新本地存储状态
					var localFileInfo = JSON.parse(localStorage.getItem(file.name)) || [];
					localFileInfo[indexCount] = {
						ctx: res.ctx,
						time: new Date().getTime(),
						offset: info.offset,
						percent: file.percent
					};
					indexCount++;
					localStorage.setItem(file.name, JSON.stringify(localFileInfo));
				});

				// 每个事件监听函数都会传入一些很有用的参数，
				// 我们可以利用这些参数提供的信息来做比如更新UI，提示上传进度等操作
				uploader.bind("UploadProgress", function(uploader, file) {
					var id = file.id;
					// 更新进度条进度信息;
					var fileUploaded = file.loaded || 0;
					$(board[id]).find('#pg_' + id).css("width", file.percent + "%");
					$(board[id]).find('#pg_' + id).find("span").text(file.percent + "%");
				});

				uploader.bind("FileUploaded", function(uploader, file, info) {
					var id = file.id;
					if(resume) {
						mkFileRequest(file)
					} else {
						$(board[id]).find('#pg_' + id).css("width", "100%");
						$(board[id]).find('#pg_' + id).find("span").text("100%");
						$(board[id])
							.find(".listbtn").attr("disabled", "disabled");
						$(board[id])
							.find(".listbtn").text("上传成功");
						uploadFinish(JSON.parse(info.response), file, board[id]);
					}
				});

				function uploadFinish(res, file, board) {
					var name = file.name;
					localStorage.removeItem(name);
					var path = domain + res.key;
					var html = '<video  style="width: 280 px;height:100px;" src="' + path + '" controls="controls">' +
						'您的浏览器不支持 video 标签。' +
						'</video>';
					$(board).find("#img").html(html);
					saveInfo(file, path);
				}

				function saveInfo(file, path) {
					var url = BaseUrl + "Video?token=" + $api.getStorage("token") + "&action=add";
					var param = {
						Fpath: path,
						Fatid: 0,
						Ftype: 1,
						Fname: file.name,
						Fsize: file.size
					}
					$api.ajaxapp2(url, param, function(data) {
						$api.showtoast("上传成功！");
					});
				}

				function initFileInfo(file) {
					var localFileInfo = JSON.parse(localStorage.getItem(file.name)) || [];
					indexCount = 0;
					var length = localFileInfo.length
					if(length) {
						var clearStatus = false
						for(var i = 0; i < localFileInfo.length; i++) {
							indexCount++
							if(isExpired(localFileInfo[i].time)) {
								clearStatus = true
								localStorage.removeItem(file.name);
								break;
							}
						}
						if(clearStatus) {
							indexCount = 0;
							return
						}
						file.loaded = localFileInfo[length - 1].offset;
						var leftSize = file.size - file.loaded;
						if(leftSize < chunk_size) {
							blockSize = leftSize
						}
						file.percent = localFileInfo[length - 1].percent;
						return
					} else {
						indexCount = 0
					}
				}
				
				

				function mkFileRequest(file) {
					// 调用sdk的url构建函数
					var requestUrl = qiniu.createMkFileUrl(
						uploadUrl,
						file.size,
						key,
						putExtra
					);
					var ctx = []
					var id = file.id
					var local = JSON.parse(localStorage.getItem(file.name))
					for(var i = 0; i < local.length; i++) {
						ctx.push(local[i].ctx)
					}
					// 设置上传的header信息
					var headers = qiniu.getHeadersForMkFile(token)
					$.ajax({
						url: requestUrl,
						type: "POST",
						headers: headers,
						data: ctx.join(","),
						success: function(res) {
							uploadFinish(res, file.name, board[id]);
						}
					})
				}

				function isExpired(time) {
					var expireAt = time + 3600 * 24 * 1000;
					return new Date().getTime() > expireAt;
				}
			}

			function initQiuniu() {
				var url = BaseUrl + "Qiniu?token=" + $api.getStorage("token");
				$api.ajaxapp2(url, {}, function(res) {
					token = res.Token;
					domain = res.DoMain;
					initUpView();
				});
			}
			
			function f_save(){
				return 1;
			}
		</script>

	</head>

	<body class="mainbody">
		<form id="form1" onsubmit="return false">
			<div style="display:none" class="div-alarm"></div>
			<div class="toolbar-wrap">
				<div  class="toolbar">
					<div class="l-list">
						<ul id="icon-list" class="icon-list">
							<li>
								<a class='add' id="select"><i></i><span>添加文件</span></a>
							</li>
							<li>
								<div id="progressbar1"></div>
							</li>
						</ul>
					</div>

				</div>
			</div>
			<div style="border: 1 solid #f1f1f1;height:100%;width:100%;">

				<ul style="padding:0 5px; height:44px;line-height:44px;color:#333;background-color: #d1d1d1;">
					<li>
						<div class="aui-paiming-li-head" style="text-align: center;width: 30%;float: left;">文件名</div>
						<div class="aui-paiming-li-head" style="text-align: center;width: 10%;float: left;">文件大小</div>
						<div class="aui-paiming-li-head" style="text-align: center;width: 50%;float: left;">上传进度</div>
						<div class="aui-paiming-li-head" style="text-align: center;width: 10%;float: left;">操作</div>
					</li>
				</ul>
				<ul class="recode">

				</ul>

			</div>
		</form>

	</body>

</html>